//index.js
//获取应用实例
const app = getApp()
// 引用百度地图微信小程序JSAPI模块
const BMap = require('../../libs/bmap-wx.min.js');
var bmap;

Page({
  data: {
    searchCon:'',//输入内容
    searchResult:[],//搜索列表
    longitude:'',//经度
    latitude:'',//纬度
    mylatitude: '',//我的经度
    mylongitude: '',//我的纬度
    distance:'',//距离
    address: '我的位置',//详细地址，默认我的位置,广东省广州市
    desc: '',//地址描述，在这里获取景点名
    business: '',//商圈
    scale: 16,//地图的扩大倍数
    markers: [{ //标记点用于在地图上显示标记的位置
      id: 1,
      latitude: '',
      longitude: '',
      iconPath: '../public/image/location.png',
      width: 1,
      height: 1,
      callout: {
        content: '自定义点',
        color: '#fff',
        bgColor: '#66DFB4',
        fontSize: '16',
        borderRadius: '5',
        padding: '20'
      }
    }],
    list:"",
    userid:'4661618b-4583-4850-9430-5917c55702a9',
    scenicid:'1200'
  },

  goList: function(e){
    var address = e.currentTarget.dataset.address
    //console.log(address)
    wx.navigateTo({
      url: '/pages/attractionsList/attractionsList?address='+address
      })
  },

  goPageEdit: function(e){
    wx.navigateTo({
      url: '/pages/edit2/edit2?userId='+this.data.userid+'&scenicId='+this.data.scenicid
      })
  },
  
  //事件处理函数
  onLoad: function (options) {
    const that = this;


    // 实例化百度地图API核心类
    bmap = new BMap.BMapWX({
      ak: app.globalData.ak
    })

    //获取当前位置经纬度
  app.getLocation(function (location) {
      var str = 'markers[0].longitude', str2 = 'markers[0].latitude';
      console.log("当前位置："+location.longitude+","+location.latitude);
      that.setData({
        longitude: location.longitude,
        mylongitude: location.longitude,
        latitude: location.latitude,
        mylatitude: location.latitude,
        distance: '0',
        [str]: location.longitude,
        [str2]: location.latitude,
      });
      that.regeocoding(); //根据经纬度-》解析地址名称
    })
  },

  //回到当前位置
  tapMyPoit(){
      console.log("回到当前位置");
      var that = this;
      app.getLocation(function (location) {
      console.log(location)
      var str = 'markers[0].longitude', str2 = 'markers[0].latitude';
      console.log("当前位置："+location.latitude+","+location.longitude);
      that.setData({
        longitude: location.longitude,
        latitude: location.latitude,
        mylongitude: location.longitude,
        mylatitude: location.latitude,
        distance: '0',
        address: '我的位置',
        [str]: location.longitude,
        [str2]: location.latitude,
      });
      that.regeocoding(); //根据经纬度-》解析地址名称
    });
  },

    //计算经纬度距离函数
    distances: function (la1, lo1, la2, lo2) {
      var La1 = la1 * Math.PI / 180.0;
      var La2 = la2 * Math.PI / 180.0;
      var La3 = La1 - La2;
      var Lb3 = lo1 * Math.PI / 180.0 - lo2 * Math.PI / 180.0;
      var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2)));
      s = s * 6378.137;
      s = Math.round(s * 10000) / 10000;
      s = s.toFixed(2);
      return s;
    },

  // markets
  getLngLat(){
    var that = this; 
    this.mapCtx = wx.createMapContext("myMap"); 
    var latitude, longitude;
    this.mapCtx.getCenterLocation({ 
      success: function (res) { 
        latitude = res.latitude;
        longitude = res.longitude;
        var str = 'markers[0].longitude', str2 = 'markers[0].latitude';
        that.setData({ 
          longitude: res.longitude, 
          latitude: res.latitude, 
          [str]: res.longitude,
          [str2]: res.latitude,
        })
        that.regeocoding(); //根据经纬度-》解析地址名称 
      } 
    })

    //修改坐标位置 
    this.mapCtx.translateMarker({
      markerId: 1,
      autoRotate: true,
      duration: 1000,
      destination: {
        latitude: latitude,
        longitude: longitude,
      },
      animationEnd() {
        console.log('修改坐标位置 end')
      }
    })
  },

  //地图视野变化触发的事件
  regionchange(e) {
    console.log('地图视野变化')
    // 地图发生变化的时候，获取中间点，也就是用户选择的位置
    if (e.type == 'end' && (e.causedBy == 'scale' || e.causedBy == 'drag')) {
      this.getLngLat();
    }
  },
  markertap(e) {
    console.log(e.markerId)
    console.log(e);
  },
  controltap(e) {
    console.log(e.controlId)
  },
  
  // 发起regeocoding逆地址解析 -- 从经纬度转换为地址信息
  regeocoding(){
    console.log("地址转换开始")
    var that = this;
    console.log(that.data.latitude+','+that.data.longitude)
    
    //距离计算
    console.log("我的经纬度",that.data.mylatitude,that.data.mylongitude)
    var distance=that.distances(that.data.latitude,that.data.longitude,that.data.mylatitude,that.data.mylongitude)
    console.log("距离：",distance)
    that.setData({
      distance: distance
    })
      
  //地址转换
  bmap.regeocoding({
    location:that.data.latitude+','+that.data.longitude,
    // latitude:that.data.latitude,
    // longitude:that.data.longitude,
    success: function(res){
      // console.log(location);
      //获取地址标题
      var desc = res.wxMarkerData[0].desc
      desc = desc.split(",")
      desc = desc[0]
      if(desc.charAt(desc.length - 1)=="内"){
        desc = desc.replace("内","");
      }
      console.log("-----------",desc.indexOf("东"||"南"||"西"||"北"||"附近"))
      var splits = ["东","南","西","北","附近"]
      var tr = desc
      console.log(tr)
      for(var i=0;i<splits.length;i++){
        console.log(splits[i]);
        console.log(tr)
        if(desc.indexOf(splits[i]) != -1){
          if(desc.indexOf(splits[i])>3){
            console.log(splits[i]);
            tr = desc.match(new RegExp(/(\S*)"+splits[i]+"/));
            console.log(tr)
          }
        }
      }

      var address_s = res.wxMarkerData[0].address
      address_s = address_s.match(new RegExp(/(\S*)市/))+"市";
      address_s = address_s.split(",")
    
      console.log(tr)

      if(!tr){
        tr=res.wxMarkerData[0].desc
      }

      that.setData({
        address: address_s[0],
        desc: tr,
        business: res.wxMarkerData[0].business
      })
    },
    fail: function(res){
      // that.tipsModal('请开启位置服务权限并重试!')
      console.log("获取地址失败")
      console.log(res)
    },     
    });
    },
    //提示
  tipsModal: function (msg) {
    wx.showModal({
      title: '提示',
      content: msg,
      showCancel: false,
      confirmColor: '#2FB385'
    })
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})